

import React, { FC, useEffect, useState,useRef  } from 'react'
import MyHead from '../../components/MyHead'
import { useDispatch, useSelector } from 'react-redux'
import { changeAddress, changeCount, data_address, data_count } from '../../rtk/reducers/dataSlice'
import { getAreaAPI, getCityAPI, getLocationAPI, getMZCityAPI, getProvinceAPI } from '../../api/city'
import { TreeSelect , IndexBar , List , ErrorBlock  } from 'antd-mobile'
import { useCommonFunc } from '../../hooks/useCommon'
import { SearchBar } from 'antd-mobile'
import { IndexBarRef } from 'antd-mobile/es/components/index-bar'
import './index.scss'

const City: FC = () => {

  const [searchList,setSearchList] = useState<any>([])
  const indexBarRef = useRef<IndexBarRef>(null)
  const charCodeOfA = 'A'.charCodeAt(0)
  const groups = Array(26)
      .fill('')
      .map((_, i) => ({
          title: String.fromCharCode(charCodeOfA + i),
      }))  // A-Z
  const [toggle, setToggle] = useState<boolean>(true)
  const [cityList, setCityList] = useState<any>([])
  const { gotopage } = useCommonFunc()
  const address = useSelector(data_address)
  const dispatch = useDispatch()
  const [list, setList] = useState<any>([])
  const getLocation = async () => {
      let res = await getLocationAPI({
          provinceName: '湖北省'
      })
  }

  const getProvince = async () => {
      let res:any = await getProvinceAPI()
      if (res.code == 200) {
          setList(res.data)
      }
  }

  const getCity = async (options: any) => {
      let res:any = await getCityAPI(options)
      if (res.code == 200 && res.data.length) {
          list.forEach((item: any) => {
              if (item.name == options.provinceName) {
                  item.children = res.data;
              }
          })
          setList([...list])
      }
  }

  const getArea = async (options: any) => {
      let res:any = await getAreaAPI({
          provinceName: options.provinceName,
          cityName: options.cityName,
      })
      if (res.code == 200) {
          list.forEach((item: any) => {
              if (item.id == options.value[0]) {  // 找到省份 
                  item.children.forEach((v: any) => {
                      if (v.id == options.value[1]) {  // 找到市
                          v.children = res.data
                      }
                  })
              }
          })
      }

      setList([...list])
  }

  const getCityListData = async () => {
      let res = await getMZCityAPI()
      console.log(res);
      
      // setCityList(res.data.cities)
  }

  const onCancel = () => {
      setToggle(true)
  }

  
  const todoSearch = (keyword:any) => {
      setToggle(false)
      console.log(keyword)
      var list = cityList.filter((item:any)=>(item.pinyin.indexOf(keyword)>-1 || item.name.indexOf(keyword)>-1  ))
      console.log(list)
      setSearchList([...list])
  }
  const chooseCity = (city:any)=>{
      dispatch(changeAddress({
          city:{
              name:city.name,
              id:city.cityId
          }
      }))

      gotopage(-1)
  }
  useEffect(() => {
      // getLocation()
      // getProvince()

      getCityListData()

      
  }, [])



    return (
        <div className='spage city' style={{width:"100%",height:'100%'}}>
            <MyHead title={address ? '城市切换-' + address.city.name : '城市选择'} ></MyHead>

            <div className='city-box'>
                <div className="search" style={{ padding: '10px' }}>
                    <SearchBar onCancel={onCancel} onSearch={todoSearch} placeholder='请输入名字或者拼音' showCancelButton />
                </div>
                {
                    toggle ? <div className="city-list">
                        <div className="hot-city">
                            <h2 className="title" style={{ padding: '10px 10px', }}>
                                热门城市
                            </h2>

                            <div className="hot-list" style={{ display: "flex", flexWrap: "wrap", padding: "0 10px" }}>
                                {
                                    cityList.filter((v: any) => v.isHot == 1).map((item: any, index: number) => {
                                        return (
                                            <div onClick={()=>chooseCity(item)} key={index} className='hot-item' style={{ margin: 10, width: '26%', height: 30, lineHeight: '30px', textAlign: 'center', background: '#f4f4f4', color: '#333' }}>
                                                {item.name}
                                            </div>
                                        )
                                    })
                                }
                            </div>
                        </div>
                        <div className="clist" style={{ height: window.innerHeight }}>
                            <IndexBar ref={indexBarRef}>
                                {groups.map(group => {
                                    const { title } = group
                                    return (
                                        <IndexBar.Panel
                                            index={title}
                                            title={`标题${title}`}
                                            key={`标题${title}`}
                                        >
                                            <List>
                                                {   cityList.filter((v:any)=>v.pinyin.indexOf(title.toLowerCase())==0).map((item:any, index:number) => (
                                                    <List.Item  onClick={()=>chooseCity(item)} key={index}>{item.name}</List.Item>
                                                ))}
                                            </List>
                                        </IndexBar.Panel>
                                    )
                                })}
                            </IndexBar>
                        </div>
                    </div>
                        :
                        <div className="city-search" >
                            {
                                searchList.length>0?
                                <div className="slist">
                                    <List>
                                        {   searchList.map((item:any, index:number) => (
                                            <List.Item  onClick={()=>chooseCity(item)} key={index}>{item.name}</List.Item>
                                        ))}
                                    </List>
                                </div>
                                :
                                <div className="empty" style={{ padding: '50px 0' }}>
                                    <ErrorBlock status='empty' 
                                        title="搜索不到对应的城市"
                                        description=""
                                    />
                                </div>
                            }
                        </div>
                }
            </div>

        </div>
    )
}

export default City